import 'dart:convert';

import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:wanxiang_app/bean/order_detail_entity.dart';
import 'package:wanxiang_app/utils/common.dart';
import '../../bean/simple_entity.dart';
import '../../utils/constant.dart';
import '../../utils/network_manager.dart';
import '../../utils/network_url.dart';
import '../../utils/toast_util.dart';
import '../../utils/user_util.dart';
import '../../widgets/myappbar.dart';
import 'package:get/get.dart';

import '../../widgets/simple_dialog.dart';


class OrderDetailController extends GetxController{
  int type = 11;
  String channel_id = '';
  String order_id = '';
  bool isInital = false;
  @override
  void onInit() {
    super.onInit();

    Map map = Get.arguments;
    channel_id = map['channel_id'];
    order_id = map['order_id'];
    _getService();
  }
  @override
  void onClose() {
    super.onClose();
  }
  late OrderDetailData orderDetail;
  void _getService(){
    DioManager.getInstance().post(ServiceUrl.orderDetail,{
      "user_name": UserUtil.getUSER()?.userName,
      "channel_id": channel_id,
      "order_id": order_id,
    }, (data) async {
      OrderDetailEntity bannerEntity = OrderDetailEntity.fromJson(jsonDecode(data));
      orderDetail = bannerEntity.data;
      if(bannerEntity.code ==200){
        isInital = true;
      }else{
        ToastUtil.show(bannerEntity.msg);
      }

      update();
    }, (error) {
      ToastUtil.show(error);
    });
  }
  void _cancelOrder(context ,cid,oid){

    showDialog(context: context, builder: (BuildContext context1) {
      return MySimpleDialog(callBack: (String content) {
        if(content == 'cancel'){
          Navigator.pop(context1);
        }else if(content == 'sure'){
          Navigator.pop(context1);
          DioManager.getInstance().post(ServiceUrl.cancelOrder,{
            "user_name": UserUtil.getUSER()?.userName,
            "channel_id": cid.toString(),
            "order_id": oid.toString()
          }, (data) async {
            SimpleEntity bannerEntity = SimpleEntity.fromJson(jsonDecode(data));
            ToastUtil.show(bannerEntity.msg);
            _getService();
            update();
          }, (error) {
            ToastUtil.show(error);
          });

        }
      },
        msg: "是否立即取消订单？",
        sureText: "确定",
      );
    });
  }
  void _buyNow(context,cid,gid){
    showDialog(context: context, builder: (BuildContext context1) {
      return MySimpleDialog(callBack: (String content) {
        if(content == 'cancel'){
          Navigator.pop(context1);
        }else if(content == 'sure'){
          Navigator.pop(context1);
          DioManager.getInstance().post(ServiceUrl.sureOrder,{
            "user_name": UserUtil.getUSER()?.userName,
            "channel_id": cid.toString(),
            "goods_id": gid.toString(),
            "buy_type":3
          }, (data) async {
            SimpleEntity bannerEntity = SimpleEntity.fromJson(jsonDecode(data));
            ToastUtil.show(bannerEntity.msg);
            _getService();
            update();
          }, (error) {
            ToastUtil.show(error);
          });
        }
      },
        msg: "是否立即支付该订单？",
        sureText: "确定",
      );
    });
  }
  void _sureOrder(context,cid,oid){

    showDialog(context: context, builder: (BuildContext context1) {
      return MySimpleDialog(callBack: (String content) {
        if(content == 'cancel'){
          Navigator.pop(context1);
        }else if(content == 'sure'){
          Navigator.pop(context1);
          DioManager.getInstance().post(ServiceUrl.sureOrder,{
            "user_name": UserUtil.getUSER()?.userName,
            "channel_id": cid.toString(),
            "order_id": oid.toString()
          }, (data) async {
            SimpleEntity bannerEntity = SimpleEntity.fromJson(jsonDecode(data));
            ToastUtil.show(bannerEntity.msg);
            _getService();
            update();
          }, (error) {
            ToastUtil.show(error);
          });
        }
      },
        msg: "是否确认该订单？",
        sureText: "确定",
      );
    });


  }
  var index = 0.obs;
}




class OrderDetailPage extends GetView<OrderDetailController>  {

  late OrderDetailController controller ;
  late BuildContext context ;
  @override
  Widget build(BuildContext context1) {
    Get.lazyPut<OrderDetailController>(() => OrderDetailController());
    controller = Get.find();
    context = context1;

    return GetBuilder<OrderDetailController>(
      builder: (_){
        return  Scaffold(
            appBar: MyAppBar(context: context, title: controller.isInital?Common.orderStatusToText(controller.orderDetail.status) :'',hasLeading: true,),
            backgroundColor: Colors.white,
            body:_content());
      },
    );
  }

  Widget _content(){
    return !controller.isInital?Container(): Container(
      child: Stack(
        children: [
          Column(
            children: [
              SizedBox(height: 8.h,),
              _gameItems(),
              SizedBox(height: 8.h,),
              _info()
            ],
          ),

          Positioned(
              bottom: 0,
              child:  _status())
        ],
      ) ,
    );
  }

  Widget _gameItems(){
    return
      InkWell(
          onTap: (){
            // Get.to(()=>DetailPage());
          },
          child: Container(
            color: Colors.white,
            padding: EdgeInsets.only(left: 16.w,right: 13.w,top: 24.h),
            child:
            Column(
              children: [
                Row(
                  children: [
                    Container(
                        width: 100.w,
                        height: 78.h,
                        child: Stack(
                          children: [
                            _officer(),
                            ClipRRect(
                                borderRadius: BorderRadius.circular(10.r),
                              child:  Image.network(Common.realPicPath(controller.orderDetail.imgUrl),width: 100.w,height: 78.h,fit: BoxFit.cover,)
                            )
                          ],
                        )

                    ),
                    SizedBox(width: 14.w,),
                    Container(
                        width: MediaQuery.of(context).size.width - 29.w - 14.w - 100.w,
                        child:  Column(
                          crossAxisAlignment: CrossAxisAlignment.start,
                          children: [
                            Text(controller.orderDetail.title,
                              style: TextStyle(color: Color(0xFF333333),fontSize: 14.sp,),maxLines: 1,    textAlign: TextAlign.left,
                              overflow: TextOverflow.ellipsis,),
                            SizedBox(height: 10.h,),
                            Text('区服：${controller.orderDetail.categoryText}',style: TextStyle(color: Color(0xFF666666),fontSize: 13.sp),),
                            SizedBox(height: 6.h,),
                            Row(
                              mainAxisAlignment: MainAxisAlignment.spaceBetween,
                              children: [
                                Row(
                                  children: [
                                    _second(controller.orderDetail.isMsg),
                                    _fenqi(controller.orderDetail.isBystages)
                                  ],
                                )
                                ,
                                Row(
                                  children: [
                                    Text('¥',style: TextStyle(color: Color(0xFFFF0000),fontSize: 12.sp),),
                                    // {controller.orderDetail.realityPrice.isEmpty?controller.orderDetail.sellPrice:controller.orderDetail.realityPrice}
                                    Text(controller.orderDetail.realityPrice.isEmpty?controller.orderDetail.sellPrice:controller.orderDetail.realityPrice,style: TextStyle(color: Color(0xFFFF0000),fontSize: 18.sp),),
                                  ],
                                )

                              ],
                            )
                          ],
                        )
                    )
                  ],
                ),
                SizedBox(height: 11.h,)
              ],
            )
            ,
          )
      )
    ;
  }

  Widget _info(){
    return Container(
      color: Colors.white,
      padding: EdgeInsets.fromLTRB(16.w, 19.h, 16.w, 100.h),
      child:
      Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Row(
            children: [
              Container(
                width: 4.w,
                height: 14.h,
                decoration: BoxDecoration(
                    color: Color(0xFF007BE5)
                ),
              ),
              SizedBox(width: 10.w,),
              Text('订单详情',style: TextStyle(
                  color: Color(0xFF333333),
                  fontSize: 14.sp,
                  fontWeight: FontWeight.bold
              ),)
            ],
          ),
          SizedBox(height: 10.h,),
    Obx(() => Column(
      mainAxisAlignment: MainAxisAlignment.start,
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        SizedBox(height: 10.h,),
        _text('订单编号：${controller.orderDetail.id}'),
        SizedBox(height: 10.h,),
        _text('下单时间：${Common.transferDate(controller.orderDetail.traTime) }'),
        SizedBox(height: 10.h,),
        _text('交易支付号：${controller.orderDetail.paycode}'),
        controller.orderDetail.sellUserid==UserUtil.getUSER()?.userId?
        SizedBox(height: 10.h,):Container(),
        controller.orderDetail.sellUserid==UserUtil.getUSER()?.userId?
        _text('实付金额：${controller.orderDetail.realityPrice.isEmpty?controller.orderDetail.sellPrice:controller.orderDetail.realityPrice}元'):Container(),
        SizedBox(height: 10.h,),
        _text('退款至：原路返回'),
        SizedBox(height: 10.h,),
        _text('平台收取手续费：${controller.orderDetail.sxPrice}'),
      ],
    )),

        ],
      )
    );
  }

  Widget _text(text){
    controller.index.value =  controller.index.value +1;
    return    Text('${ controller.index.value}.$text',style: TextStyle(color: Color(0xFF666666),fontSize: 13.sp),);
  }

  Widget _status(){
    if(controller.orderDetail.status==11){
      return _bottom();
    }
    // if(controller.orderDetail.status==12){
    //   return _bottom1213('取消订单');
    // }
    if(controller.orderDetail.status==13){
      return _bottom1213('确认收货');
    }
    return Container();
  }

  Widget _bottom(){
    return Container(
      height: 71.h,
      padding: EdgeInsets.only(top:10.h ),
      width: MediaQuery.of(context).size.width,
      color: Colors.white,
      alignment: Alignment.center,
      child: Row(
        mainAxisAlignment: MainAxisAlignment.center,
        children: [

     //      InkWell(
     //        onTap:(){
     //          controller._cancelOrder(context,controller.orderDetail.channelId,controller.orderDetail.id);
     //      },
     //        child: Container(
     //          width: 142.w,
     //          height: 42.h,
     //          alignment: Alignment.center,
     //          decoration: BoxDecoration(
     //              color: Color(0xFF7D87FA),
     //              borderRadius: BorderRadius.circular(6.r)
     //          ),
     //          child: Text('取消订单',style: TextStyle(
     //              color: Colors.white,
     //              fontSize: 13.sp
     //          ),),
     //        )
     //      )
     //
     // ,
     //      SizedBox(width: 18.w,),
          InkWell(
            onTap: (){
              controller._buyNow(context,controller.orderDetail.channelId,controller.orderDetail.id);
            },
            child:  Container(
              width: 142.w,
              height: 42.h,
              alignment: Alignment.center,
              decoration: BoxDecoration(
                  color: Color(0xFFF43F50),
                  borderRadius: BorderRadius.circular(6.r)
              ),
              child: Text('立即支付',style: TextStyle(
                  color: Colors.white,
                  fontSize: 13.sp
              ),),
            )
          )
         ,
        ],
      ),
    );
  }

  Widget _bottom1213(text){
    return InkWell(
      onTap: (){
        if(text=='取消订单'){
          controller._cancelOrder(context,controller.orderDetail.channelId,controller.orderDetail.id);
        }else if(text=='立即支付'){
          controller._buyNow(context,controller.orderDetail.channelId,controller.orderDetail.id);
        }else if(text=='确认收货'){
          controller._sureOrder(context,controller.orderDetail.channelId,controller.orderDetail.id);
        }
      },
      child: Container(
        height: 71.h,
        padding: EdgeInsets.only(top:10.h ),
        width: MediaQuery.of(context).size.width,
        color: Colors.white,
        alignment: Alignment.center,
        child: Row(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            Container(
              width: 280.w,
              height: 42.h,
              alignment: Alignment.center,
              decoration: BoxDecoration(
                  color: Color(0xFFF43F50),
                  borderRadius: BorderRadius.circular(6.r)
              ),
              child: Text(text,style: TextStyle(
                  color: Colors.white,
                  fontSize: 13.sp
              ),),
            ),
          ],
        ),
      )
    ) ;
  }


  Widget _second(msg1){
    String msg = '不包人脸';
    if(msg1==1){
      msg = '可二次';
    }
    if(msg1==2){
      msg = '可包人脸';
    }
    return Container(
      width: 55.w,
      height: 20.h,
      margin: EdgeInsets.only(right: 5.w),
      alignment: Alignment.center,
      decoration: BoxDecoration(
          borderRadius: BorderRadius.circular(14.r),
          border: Border.all(width: 1.w,color: Color(0xFF4EBCFF))
      ),
      child: Text(msg,style: TextStyle(
          color: Color(0xFF4EBCFF),
          fontSize: 12.sp
      ),),
    );
  }

  Widget _fenqi(msg1){
    String msg = '不可分期';
    if(msg1=='1'){
      msg = '可分期';
    }
    return Container(
      width: 55.w,
      height: 20.h,
      alignment: Alignment.center,
      decoration: BoxDecoration(
          borderRadius: BorderRadius.circular(14.r),
          border: Border.all(width: 1.w,color: Color(0xFF4EBCFF))
      ),
      child: Text(msg,style: TextStyle(
          color: Color(0xFF4EBCFF),
          fontSize: 12.sp
      ),),
    );
  }

  Widget _officer() {
    return Container(
      child: Image.asset(Constant.IMG_BASE+'baopei.png',width: 52.w,height: 17.h,fit: BoxFit.fitWidth,),
    );
  }

}